﻿using System;
using System.IO;
using System.Net;
using System.Xml.Linq;

using TVersityDotNet.Providers;

namespace TVersityDotNet
{
    /// <summary>
    /// Class to take care of HTTP communications
    /// </summary>
    class MessageManager : IMessageManager
    {
        /// <summary>
        /// The base URL where commands should be sent to
        /// </summary>
        public Uri BaseUrl { get; set; }

        /// <summary>
        /// The provider used to connect to 
        /// </summary>
        protected IRestProvider RestProvider { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="baseUrl">The base URL where commands should be sent to</param>
        public MessageManager(Uri baseUrl)
        {
            this.BaseUrl = baseUrl;
            if (this.RestProvider == null)
            {
                this.RestProvider = new TVersityRestProvider();
            }
        }

        /// <summary>
        /// Constructor, with IRestProvider initializer
        /// </summary>
        /// <param name="baseUrl">URL of the API</param>
        /// <param name="restProvider">Rest Provider in use</param>
        public MessageManager(Uri baseUrl, IRestProvider restProvider)
            : this(baseUrl)
        {
            this.RestProvider = restProvider;
        }

        /// <summary>
        /// Method used to send the TVersityRequest to the REST Endpoint, through HTTP
        /// </summary>
        /// <param name="request">The TVersityRequest to process</param>
        /// <returns>A TVersityResponse of the proper type</returns>
        public TVersityResponse ProcessRequest(TVersityRequest request)
        {            
            string url = string.Concat(this.BaseUrl, request.RequestString);
            StreamReader responseStream = new StreamReader(this.RestProvider.Get(url));
            return request.CreateResponse(XDocument.Load(responseStream));
        }
    }
}
